Micron Document
`:top
The `!syntax of Java`! is `F33f`_`[the set of rules`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Syntax]`_`f defining how a `F33f`_`[Java`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Java_(programming_language)]`_`f program is written and interpreted.

The `F33f`_`[syntax`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Syntax_(programming_languages)]`_`f is mostly derived from `F33f`_`[C`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C_(programming_language)]`_`f and `F33f`_`[C++`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C++]`_`f. Unlike C++, Java has no global functions or variables, but has data members which are also regarded as `F33f`_`[global variables`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Global_variable]`_`f. All code belongs to `F33f`_`[classes`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Class_(computer_programming)]`_`f and all values are `F33f`_`[objects`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Object_(computer_science)]`_`f. The only exception is the `F33f`_`[primitive data types`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Primitive_data_types]`_`f, which are not considered to be objects for performance reasons (though can be automatically converted to objects and vice versa via `F33f`_`[autoboxing`#boxing-and-unboxing]`_`f). Some features like `F33f`_`[operator overloading`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Operator_overloading]`_`f or `F33f`_`[unsigned integer`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Unsigned_integer]`_`f `F33f`_`[data types`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Data_type]`_`f are omitted to simplify the language and avoid possible programming mistakes.

The Java syntax has been gradually extended in the course of numerous major `F33f`_`[JDK`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=JDK]`_`f `F33f`_`[releases`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Java_version_history]`_`f, and now supports abilities such as `F33f`_`[generic programming`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Generic_programming]`_`f and `F33f`_`[anonymous functions`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Anonymous_function]`_`f (function literals, called lambda expressions in Java). Since 2017, a new JDK version is released twice a year, with each release improving the language incrementally.

>>Contents

• `F0af`_`[Basics`#basics]`_`f
• `F0af`_`[Identifier`#identifier]`_`f
• `F0af`_`[Keywords`#keywords]`_`f
• `F0af`_`[Literals`#literals]`_`f
• `F0af`_`[Variables`#variables]`_`f
• `F0af`_`[Code blocks`#code-blocks]`_`f
• `F0af`_`[Comments`#comments]`_`f
• `F0af`_`[Universal types`#universal-types]`_`f
• `F0af`_`[Program structure`#program-structure]`_`f
• `F0af`_`[main method`#main-method]`_`f
• `F0af`_`[Packages`#packages]`_`f
• `F0af`_`[Import declaration`#import-declaration]`_`f
• `F0af`_`[Operators`#operators]`_`f
• `F0af`_`[Control structures`#control-structures]`_`f
• `F0af`_`[Conditional statements`#conditional-statements]`_`f
• `F0af`_`[Iteration statements`#iteration-statements]`_`f
• `F0af`_`[Jump statements`#jump-statements]`_`f
• `F0af`_`[Exception handling statements`#exception-handling-statements]`_`f
• `F0af`_`[Thread concurrency control`#thread-concurrency-control]`_`f
• `F0af`_`[assert statement`#assert-statement]`_`f
• `F0af`_`[Primitive types`#primitive-types]`_`f
• `F0af`_`[Boxing and unboxing`#boxing-and-unboxing]`_`f
• `F0af`_`[Reference types`#reference-types]`_`f
• `F0af`_`[Arrays`#arrays]`_`f
• `F0af`_`[Classes`#classes]`_`f
• `F0af`_`[Interfaces`#interfaces]`_`f
• `F0af`_`[Generics`#generics]`_`f
• `F0af`_`[Generic classes`#generic-classes]`_`f
• `F0af`_`[Generic methods and constructors`#generic-methods-and-constructors]`_`f
• `F0af`_`[Generic interfaces`#generic-interfaces]`_`f
• `F0af`_`[See also`#see-also]`_`f
• `F0af`_`[References`#references]`_`f
• `F0af`_`[External links`#external-links]`_`f

-─

>>Basics

>>>Identifier

An `F33f`_`[identifier`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Identifier]`_`f is the name of an element in the `F33f`_`[code`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Source_code]`_`f. There are certain standard `F33f`_`[naming conventions`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Naming_conventions_(programming)]`_`f to follow when selecting names for elements. Identifiers in Java are `F33f`_`[case-sensitive`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Case_sensitivity]`_`f.

An identifier can contain:

• Any Unicode character that is a letter (including numeric letters like `F33f`_`[Roman numerals`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Roman_numerals]`_`f) or digit.
• `F33f`_`[Currency sign`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Currency_sign]`_`f (such as ¥).
• Connecting punctuation character (such as `F33f`_`[_`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Underscore]`_`f).

An identifier cannot:

• Start with a digit.
• Be equal to a reserved keyword, null literal or `F33f`_`[Boolean`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Boolean_data_type]`_`f literal.

>>>Keywords

>>>>Keywords

The following words are keywords and cannot be used as identifiers under any circumstances.

• `B100`F9d9_`f`b
• `B100`F9d9abstract`f`b
• `B100`F9d9assert`f`b
• `B100`F9d9boolean`f`b
• `B100`F9d9break`f`b
• `B100`F9d9byte`f`b
• `B100`F9d9case`f`b
• `B100`F9d9catch`f`b
• `B100`F9d9char`f`b
• `B100`F9d9class`f`b
• `B100`F9d9continue`f`b
• `B100`F9d9default`f`b
• `B100`F9d9do`f`b
• `B100`F9d9double`f`b
• `B100`F9d9else`f`b
• `B100`F9d9enum`f`b
• `B100`F9d9extends`f`b
• `B100`F9d9final`f`b
• `B100`F9d9finally`f`b
• `B100`F9d9float`f`b
• `B100`F9d9for`f`b
• `B100`F9d9if`f`b
• `B100`F9d9implements`f`b
• `B100`F9d9import`f`b
• `B100`F9d9instanceof`f`b
• `B100`F9d9int`f`b
• `B100`F9d9interface`f`b
• `B100`F9d9long`f`b
• `B100`F9d9native`f`b
• `B100`F9d9new`f`b
• `B100`F9d9package`f`b
• `B100`F9d9private`f`b
• `B100`F9d9protected`f`b
• `B100`F9d9public`f`b
• `B100`F9d9return`f`b
• `B100`F9d9short`f`b
• `B100`F9d9static`f`b
• `B100`F9d9super`f`b
• `B100`F9d9switch`f`b
• `B100`F9d9synchronized`f`b
• `B100`F9d9this`f`b
• `B100`F9d9throw`f`b
• `B100`F9d9throws`f`b
• `B100`F9d9transient`f`b
• `B100`F9d9try`f`b
• `B100`F9d9void`f`b
• `B100`F9d9volatile`f`b
• `B100`F9d9while`f`b

>>>>Reserved identifiers

The following words are contextual keywords and are only restricted in certain contexts.

• `B100`F9d9exports`f`b
• `B100`F9d9module`f`b
• `B100`F9d9non-sealed`f`b
• `B100`F9d9open`f`b
• `B100`F9d9opens`f`b
• `B100`F9d9permits`f`b
• `B100`F9d9provides`f`b
• `B100`F9d9record`f`b
• `B100`F9d9requires`f`b
• `B100`F9d9sealed`f`b
• `B100`F9d9to`f`b
• `B100`F9d9transitive`f`b
• `B100`F9d9var`f`b
• `B100`F9d9when`f`b
• `B100`F9d9with`f`b
• `B100`F9d9yield`f`b

>>>>Reserved words for literal values

The following words refer to literal values used by the language.

• `B100`F9d9true`f`b
• `B100`F9d9false`f`b
• `B100`F9d9null`f`b

>>>>Unused

The following words are reserved as keywords, but currently have no use or purpose.

• `B100`F9d9const`f`b
• `B100`F9d9goto`f`b
• `B100`F9d9strictfp`f`b

>>>Literals

`t
| Integers | Integers |
|---|---|
| binary (introduced in Java SE 7) | 0b11110101 ( 0b followed by a binary number) |
| octal | 0365 ( 0 followed by an octal number) |
| hexadecimal | 0xF5 ( 0x followed by a hexadecimal number) |
| decimal | 245 (decimal number) |
| Floating-point values | Floating-point values |
| float | 23.5F , .5f , 1.72E3F (decimal fraction with an optional exponent indicator, followed by F ) |
| float | 0x.5FP0F , 0x.5P-6f ( 0x followed by a hexadecimal fraction with a mandatory exponent indicator and a suffix F ) |
| double | 23.5D , .5 , 5. , 1.72E3D (decimal fraction with an optional exponent indicator, followed by optional D ) |
| double | 0x.5FP0 , 0x.5P-6D ( 0x followed by a hexadecimal fraction with a mandatory exponent indicator and an optional suffix D ) |
| Character literals | Character literals |
| char | 'a' , 'Z' , '\\u0231' (character or a character escape, enclosed in single quotes) |
| Boolean literals | Boolean literals |
| boolean | true , false |
| null literal | null literal |
| null reference | null |
| String literals | String literals |
| String | "Hello, World" (sequence of characters and character escapes enclosed in double quotes) |
| Characters escapes in strings | Characters escapes in strings |
| Unicode character | \\u3876 ( \\u followed by the hexadecimal unicode code point up to U+FFFF) |
| Octal escape | \\352 (octal number not exceeding 377, preceded by backslash) |
| Line feed | \\n |
| Carriage return | \\r |
| Form feed | \\f |
| Backslash | \\\\ |
| Single quote | \\' |
| Double quote | \\" |
| Tab | \\t |
| Backspace | \\b |
`t

Integer literals are of `B100`F9d9int`f`b type by default unless `B100`F9d9long`f`b type is specified by appending `B100`F9d9L`f`b or `B100`F9d9l`f`b suffix to the literal, e.g. `B100`F9d9367L`f`b. Since Java SE 7, it is possible to include underscores between the digits of a number to increase readability; for example, a number 145608987 can be written as 145_608_987.

>>>Variables

`F33f`_`[Variables`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Variable_(computer_science)]`_`f are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.

`B100`F9d9int count; //Declaring an uninitialized variable called 'count', of type 'int'`f`b
`B100`F9d9count = 35; //Initializing the variable`f`b
`B100`F9d9int count = 35; //Declaring and initializing the variable at the same time`f`b

Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.

`B100`F9d9int a, b; //Declaring multiple variables of the same type`f`b
`B100`F9d9int a = 2, b = 3; //Declaring and initializing multiple variables of the same type`f`b

>>>>Type inference

Since Java 10, it has become possible to `F33f`_`[infer types`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Type_inference]`_`f for the variables automatically by using `B100`F9d9var`f`b.

`B100`F9d9// stream will have the FileOutputStream type as inferred from its initializer`f`b
`B100`F9d9var stream = new FileOutputStream("file.txt");`f`b
`B100`F9d9`f`b
`B100`F9d9// An equivalent declaration with an explicit type`f`b
`B100`F9d9FileOutputStream stream = new FileOutputStream("file.txt");`f`b

>>>Code blocks

The separators { and } signify a code block and a new scope. Class members and the body of a `F33f`_`[method`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Method_(computer_programming)]`_`f are examples of what can live inside these braces in various contexts.

Inside of method bodies, braces may be used to create new scopes, as follows:

`B100`F9d9void doSomething() {`f`b
`B100`F9d9 int a;`f`b
`B100`F9d9`f`b
`B100`F9d9 {`f`b
`B100`F9d9 int b;`f`b
`B100`F9d9 a = 1;`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 a = 2;`f`b
`B100`F9d9 b = 3; // Illegal because the variable b is declared in an inner scope..`f`b
`B100`F9d9}`f`b

>>>Comments

Java has three kinds of `F33f`_`[comments`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Comment_(computer_programming)]`_`f: `*traditional comments`*, `*end-of-line comments`* and `*documentation comments`*.

Traditional comments, also known as block comments, start with `B100`F9d9/*`f`b and end with `B100`F9d9*/`f`b, they may span across multiple lines. This type of comment was derived from C and C++.

`B100`F9d9/* This is a multi-line comment.`f`b
`B100`F9d9It may occupy more than one line. */`f`b

End-of-line comments start with `B100`F9d9//`f`b and extend to the end of the current line. This comment type is also present in C++ and in modern C.

`B100`F9d9// This is an end-of-line comment`f`b

Documentation comments in the source files are processed by the `F33f`_`[Javadoc`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Javadoc]`_`f tool to generate documentation. This type of comment is identical to traditional comments, except it starts with `B100`F9d9/**`f`b and follows conventions defined by the Javadoc tool. Technically, these comments are a special kind of traditional comment and they are not specifically defined in the language specification.

`B100`F9d9/**`f`b
`B100`F9d9 * This is a documentation comment.`f`b
`B100`F9d9 *`f`b
`B100`F9d9 * @author John Doe`f`b
`B100`F9d9 */`f`b

>>>Universal types

Classes in the package java.lang are implicitly imported into every program, as long as no explicitly-imported types have the same names. Important ones include:

>>>>java.lang.Object

`B100`F9d9java.lang.Object`f`b is Java's `F33f`_`[top type`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Top_type]`_`f. It is implicitly the superclass of all classes that do not declare any parent class (thus all classes in Java inherent from `B100`F9d9Object`f`b. All values can be converted to this type, although for primitive values this involves `F33f`_`[autoboxing`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Object_type_(object-oriented_programming)]`_`f.

>>>>java.lang.String

`B100`F9d9java.lang.String`f`b is Java's basic string type. `F33f`_`[Immutable`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Immutable_object]`_`f. Some methods treat each `F33f`_`[UTF-16`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=UTF-16]`_`f code unit as a "character", but methods to convert to an `B100`F9d9int[]`f`b that is effectively `F33f`_`[UTF-32`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=UTF-32]`_`f are also available.

>>>>java.lang.Throwable

`B100`F9d9java.lang.Throwable`f`b is supertype of everything that can be `F33f`_`[thrown or caught`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Exception_handling]`_`f with Java's `B100`F9d9throw`f`b and `B100`F9d9catch`f`b statements.

>>Program structure

Java applications consist of collections of classes. Classes exist in packages but can also be nested inside other classes.

>>>main method

Every Java application must have an entry point. This is true of both graphical interface applications and console applications. The entry point is the `B100`F9d9main`f`b method. There can be more than one class with a `B100`F9d9main`f`b method, but the main class is always defined externally (for example, in a `F33f`_`[manifest file`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Manifest_file]`_`f). The `B100`F9d9main`f`b method along with the main class must be declared `B100`F9d9public`f`b. The method must be `B100`F9d9static`f`b and is passed command-line arguments as an array of strings. Unlike `F33f`_`[C++`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C++]`_`f or `F33f`_`[C#`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C_Sharp_(programming_language)]`_`f, it never returns a value and must return `B100`F9d9void`f`b.

`B100`F9d9public static void main(String[] args) {`f`b
`B100`F9d9}`f`b

>>>Packages

Packages are a part of a class name and they are used to group and/or distinguish named entities from other ones. Another purpose of packages is to govern code access together with access modifiers. For example, `B100`F9d9java.io.InputStream`f`b is a fully qualified class name for the class `B100`F9d9InputStream`f`b which is located in the package `B100`F9d9java.io`f`b.

A package is declared at the start of the file with the `B100`F9d9package`f`b declaration:

`B100`F9d9package myapplication.mylibrary;`f`b
`B100`F9d9`f`b
`B100`F9d9public class MyClass {`f`b
`B100`F9d9}`f`b

Classes with the `B100`F9d9public`f`b modifier must be placed in the files with the same name and java extension and put into nested folders corresponding to the package name. The above class `B100`F9d9myapplication.mylibrary.MyClass`f`b will have the following path: `B100`F9d9myapplication/mylibrary/MyClass.java`f`b.

>>>Import declaration

>>>>Type import declaration

A type import declaration allows a named type to be referred to by a simple name rather than the full name that includes the package. Import declarations can be `*single type import declarations`* or `*import-on-demand declarations`*. Import declarations must be placed at the top of a code file after the package declaration.

`B100`F9d9package myPackage;`f`b
`B100`F9d9`f`b
`B100`F9d9import java.util.Random; // Single type declaration`f`b
`B100`F9d9`f`b
`B100`F9d9public class ImportsTest {`f`b
`B100`F9d9 public static void main(String[] args) {`f`b
`B100`F9d9 /* The following line is equivalent to`f`b
`B100`F9d9 * java.util.Random random = new java.util.Random();`f`b
`B100`F9d9 * It would have been incorrect without the import.`f`b
`B100`F9d9 */`f`b
`B100`F9d9 Random random = new Random();`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

Import-on-demand declarations are mentioned in the code. A "type import" imports all the types of the package. A "static import" imports members of the package.

`B100`F9d9import java.util.*; /*This form of importing classes makes all classes`f`b
`B100`F9d9 in package java.util available by name, could be used instead of the`f`b
`B100`F9d9 import declaration in the previous example. */`f`b
`B100`F9d9import java.*; /*This statement is legal, but does nothing, since there`f`b
`B100`F9d9 are no classes directly in package java. All of them are in packages`f`b
`B100`F9d9 within package java. This does not import all available classes.*/`f`b

>>>>Static import declaration

This type of declaration has been available since `F33f`_`[J2SE 5.0`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_5.0]`_`f. `F33f`_`[Static import`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Static_imports]`_`f declarations allow access to static members defined in another class, interface, annotation, or enum; without specifying the class name:

`B100`F9d9import static java.lang.System.out; //'out' is a static field in java.lang.System`f`b
`B100`F9d9`f`b
`B100`F9d9public class HelloWorld {`f`b
`B100`F9d9 public static void main(String[] args) {`f`b
`B100`F9d9 /* The following line is equivalent to`f`b
`B100`F9d9 System.out.println("Hi World!");`f`b
`B100`F9d9 and would have been incorrect without the import declaration. */`f`b
`B100`F9d9 out.println("Hello World!");`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

Import-on-demand declarations allow to import all the fields of the type:

`B100`F9d9import static java.lang.System.*;`f`b
`B100`F9d9 /* This form of declaration makes all`f`b
`B100`F9d9 fields in the java.lang.System class available by name, and may be used instead`f`b
`B100`F9d9 of the import declaration in the previous example. */`f`b

Enum constants may also be used with static import. For example, this enum is in the package called `B100`F9d9screen`f`b:

`B100`F9d9public enum ColorName {`f`b
`B100`F9d9 RED, BLUE, GREEN`f`b
`B100`F9d9};`f`b

It is possible to use static import declarations in another class to retrieve the enum constants:

`B100`F9d9import screen.ColorName;`f`b
`B100`F9d9import static screen.ColorName.*;`f`b
`B100`F9d9`f`b
`B100`F9d9public class Dots {`f`b
`B100`F9d9 /* The following line is equivalent to 'ColorName foo = ColorName.RED',`f`b
`B100`F9d9 and it would have been incorrect without the static import. */`f`b
`B100`F9d9 ColorName foo = RED;`f`b
`B100`F9d9`f`b
`B100`F9d9 void shift() {`f`b
`B100`F9d9 /* The following line is equivalent to`f`b
`B100`F9d9 if (foo == ColorName.RED) foo = ColorName.BLUE; */`f`b
`B100`F9d9 if (foo == RED) foo = BLUE;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>Operators

Operators in Java are similar to those in `F33f`_`[C++`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C++]`_`f. However, there is no `B100`F9d9delete`f`b operator due to `F33f`_`[garbage collection`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Garbage_collection_(computer_science)]`_`f mechanisms in Java, and there are no operations on `F33f`_`[pointers`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Pointer_(computer_programming)]`_`f since Java does not support them. Another difference is that Java has an unsigned right shift operator (`B100`F9d9>>>`f`b), while C's right shift operator's signedness is type-dependent. Operators in Java cannot be `F33f`_`[overloaded`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Operator_overloading]`_`f.

`t
| Precedence | Operator | Description | Associativity |
|---|---|---|---|
| 1 | () | Method invocation | Left-to-right |
| 1 | [] | Array access | Left-to-right |
| 1 | . | Class member selection | Left-to-right |
| 2 | ++ -- | Postfix increment and decrement [ 1 ] | Left-to-right |
| 3 | ++ -- | Prefix increment and decrement | Right-to-left |
| 3 | + - | Unary plus and minus | Right-to-left |
| 3 | ! ~ | Logical NOT and bitwise NOT | Right-to-left |
| 3 | ( type ) val | Type cast | Right-to-left |
| 3 | new | Class instance or array creation | Right-to-left |
| 4 | * / % | Multiplication, division, and modulus (remainder) | Left-to-right |
| 5 | + - | Addition and subtraction | Left-to-right |
| 5 | + | String concatenation | Left-to-right |
| 6 | << >> >>> | Bitwise left shift, signed right shift and unsigned right shift | Left-to-right |
| 7 | < <= | Relational "less than" and "less than or equal to" | Left-to-right |
| 7 | > >= | Relational "greater than" and "greater than or equal to" | Left-to-right |
| 7 | instanceof | Type comparison | Left-to-right |
| 8 | == != | Relational "equal to" and "not equal to" | Left-to-right |
| 9 | & | Bitwise and logical AND | Left-to-right |
| 10 | ^ | Bitwise and logical XOR (exclusive or) | Left-to-right |
| 11 | / | Bitwise and logical OR (inclusive or) | Left-to-right |
| 12 | && | Logical conditional-AND | Left-to-right |
| 13 | // | Logical conditional-OR | Left-to-right |
| 14 | c ? t : f | Ternary conditional (see ?: ) | Right-to-left |
| 15 | = | Simple assignment | Right-to-left |
| 15 | += -= | Assignment by sum and difference | Right-to-left |
| 15 | *= /= %= | Assignment by product, quotient, and remainder | Right-to-left |
| 15 | <<= >>= >>>= | Assignment by bitwise left shift, signed right shift and unsigned right shift | Right-to-left |
| 15 | &= ^= /= | Assignment by bitwise AND, XOR, and OR | Right-to-left |
`t

>>Control structures

>>>Conditional statements

>>>>if statement

`F33f`_`[if statements`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Conditional_(computer_programming)]`_`f in Java are similar to those in C and use the same syntax:

`B100`F9d9if (i == 3) {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9}`f`b

`B100`F9d9if`f`b statement may include optional `B100`F9d9else`f`b block, in which case it becomes an if-then-else statement:

`B100`F9d9if (i == 3) {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9} else {`f`b
`B100`F9d9 doSomethingElse();`f`b
`B100`F9d9}`f`b

Like C, else-if construction does not involve any special keywords, it is formed as a sequence of separate if-then-else statements:

`B100`F9d9if (i == 3) {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9} else if (i == 2) {`f`b
`B100`F9d9 doSomethingElse();`f`b
`B100`F9d9} else {`f`b
`B100`F9d9 doSomethingDifferent();`f`b
`B100`F9d9}`f`b

Also, a `F33f`_`[?:`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=?:]`_`f operator can be used in place of simple if statement, for example

`B100`F9d9int a = 1;`f`b
`B100`F9d9int b = 2;`f`b
`B100`F9d9int minVal = (a < b) ? a : b;`f`b

>>>>switch statement

`F33f`_`[Switch statements`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Switch_statement]`_`f in Java can use `B100`F9d9byte`f`b, `B100`F9d9short`f`b, `B100`F9d9char`f`b, and `B100`F9d9int`f`b (not `B100`F9d9long`f`b) primitive data types or their corresponding wrapper types. Starting with J2SE 5.0, it is possible to use `F33f`_`[enum types`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Enumerated_type]`_`f. Starting with Java SE 7, it is possible to use Strings.`:cite-ref-2[`F5bf`_`[2`#cite-note-2]`_`f] Other `F33f`_`[reference types`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Reference_type]`_`f cannot be used in `B100`F9d9switch`f`b statements.

Possible values are listed using `B100`F9d9case`f`b labels. These labels in Java may contain only constants (including enum constants and string constants). Execution will start after the label corresponding to the expression inside the brackets. An optional `B100`F9d9default`f`b label may be present to declare that the code following it will be executed if none of the case labels correspond to the expression.

Code for each label ends with the `B100`F9d9break`f`b keyword. It is possible to omit it causing the execution to proceed to the next label, however, a warning will usually be reported during compilation.

`B100`F9d9switch (ch) {`f`b
`B100`F9d9 case 'A':`f`b
`B100`F9d9 doSomething(); // Triggered if ch == 'A'`f`b
`B100`F9d9 break;`f`b
`B100`F9d9 case 'B':`f`b
`B100`F9d9 case 'C':`f`b
`B100`F9d9 doSomethingElse(); // Triggered if ch == 'B' or ch == 'C'`f`b
`B100`F9d9 break;`f`b
`B100`F9d9 default:`f`b
`B100`F9d9 doSomethingDifferent(); // Triggered in any other case`f`b
`B100`F9d9 break;`f`b
`B100`F9d9}`f`b

>>>>switch expressions

Since Java 14 it has become possible to use switch expressions, which use the new arrow syntax:

`B100`F9d9var result = switch (ch) {`f`b
`B100`F9d9 case 'A' -> Result.GREAT;`f`b
`B100`F9d9 case 'B', 'C' -> Result.FINE;`f`b
`B100`F9d9 default -> throw new ThisIsNoGoodException();`f`b
`B100`F9d9};`f`b

Alternatively, there is a possibility to express the same with the `B100`F9d9yield`f`b statement, although it is recommended to prefer the arrow syntax because it avoids the problem of accidental fall throughs.

`B100`F9d9var result = switch (ch) {`f`b
`B100`F9d9 case 'A':`f`b
`B100`F9d9 yield Result.GREAT;`f`b
`B100`F9d9 case 'B':`f`b
`B100`F9d9 case 'C':`f`b
`B100`F9d9 yield Result.FINE;`f`b
`B100`F9d9 default:`f`b
`B100`F9d9 throw new ThisIsNoGoodException();`f`b
`B100`F9d9};`f`b

>>>Iteration statements

Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true. Since `F33f`_`[J2SE 5.0`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_5.0]`_`f, Java has four forms of such statements. The condition must have type boolean or Boolean, meaning C's

`B100`F9d9while (1) {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9}`f`b

results in a compilation error.

>>>>while loop

In the `B100`F9d9while`f`b loop, the test is done before each iteration.

`B100`F9d9while (i < 10) {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9}`f`b

>>>>do ... while loop

In the `B100`F9d9do ... while`f`b loop, the test is done after each iteration. Consequently, the code is always executed at least once.

`B100`F9d9// doSomething() is called at least once`f`b
`B100`F9d9do {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9} while (i < 10);`f`b

>>>>for loop

`B100`F9d9for`f`b loops in Java include an initializer, a condition and a counter expression. It is possible to include several expressions of the same kind using comma as delimiter (except in the condition). However, unlike C, the comma is just a delimiter and not an operator.

`B100`F9d9for (int i = 0; i < 10; i++) {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// A more complex loop using two variables`f`b
`B100`F9d9for (int i = 0, j = 9; i < 10; i++, j -= 3) {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9}`f`b

Like C, all three expressions are optional. The following loop is infinite:

`B100`F9d9for (;;) {`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9}`f`b

>>>>Enhanced for loop

`F33f`_`[Enhanced for loops`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Enhanced_for_loop]`_`f have been available since `F33f`_`[J2SE 5.0`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_5.0]`_`f. This type of loop uses built-in iterators over arrays and collections to return each item in the given collection. Every element is returned and reachable in the context of the code block. When the block is executed, the next item is returned until there are no items remaining. Unlike `F33f`_`[C#`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C_Sharp_(programming_language)]`_`f, this kind of loop does not involve a special keyword, but instead uses a different notation style.

`B100`F9d9for (int i : intArray) {`f`b
`B100`F9d9 doSomething(i);`f`b
`B100`F9d9}`f`b

>>>Jump statements

>>>>Labels

Labels are given points in code used by `B100`F9d9break`f`b and `B100`F9d9continue`f`b statements. The Java `B100`F9d9goto`f`b keyword cannot be used to jump to specific points in code.

`B100`F9d9start:`f`b
`B100`F9d9someMethod();`f`b

>>>>break statement

The `B100`F9d9break`f`b statement breaks out of the closest loop or `B100`F9d9switch`f`b statement. Execution continues in the statement after the terminated statement, if any.

`B100`F9d9for (int i = 0; i < 10; i++) {`f`b
`B100`F9d9 while (true) {`f`b
`B100`F9d9 break;`f`b
`B100`F9d9 }`f`b
`B100`F9d9 // Will break to this point`f`b
`B100`F9d9}`f`b

It is possible to break out of the outer loop using labels:

`B100`F9d9outer:`f`b
`B100`F9d9for (int i = 0; i < 10; i++) {`f`b
`B100`F9d9 while (true) {`f`b
`B100`F9d9 break outer;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9// Will break to this point`f`b

>>>>continue statement

The `B100`F9d9continue`f`b statement discontinues the current iteration of the current control statement and begins the next iteration. The following `B100`F9d9while`f`b loop in the code below reads characters by calling `B100`F9d9getChar()`f`b, skipping the statements in the body of the loop if the characters are spaces:

`B100`F9d9int ch;`f`b
`B100`F9d9while (ch == getChar()) {`f`b
`B100`F9d9 if (ch == ' ') {`f`b
`B100`F9d9 continue; // Skips the rest of the while-loop`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 // Rest of the while-loop, will not be reached if ch == ' '`f`b
`B100`F9d9 doSomething();`f`b
`B100`F9d9}`f`b

Labels can be specified in `B100`F9d9continue`f`b statements and `B100`F9d9break`f`b statements:

`B100`F9d9outer:`f`b
`B100`F9d9for (String str : stringsArr) {`f`b
`B100`F9d9 char[] strChars = str.toCharArray();`f`b
`B100`F9d9 for (char ch : strChars) {`f`b
`B100`F9d9 if (ch == ' ') {`f`b
`B100`F9d9 /* Continues the outer cycle and the next`f`b
`B100`F9d9 string is retrieved from stringsArr */`f`b
`B100`F9d9 continue outer;`f`b
`B100`F9d9 }`f`b
`B100`F9d9 doSomething(ch);`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>>>return statement

The `B100`F9d9return`f`b statement is used to end method execution and to return a value. A value returned by the method is written after the `B100`F9d9return`f`b keyword. If the method returns anything but `B100`F9d9void`f`b, it must use the `B100`F9d9return`f`b statement to return some value.

`B100`F9d9void doSomething(boolean streamClosed) {`f`b
`B100`F9d9 // If streamClosed is true, execution is stopped`f`b
`B100`F9d9 if (streamClosed) {`f`b
`B100`F9d9 return;`f`b
`B100`F9d9 }`f`b
`B100`F9d9 readFromStream();`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9int calculateSum(int a, int b) {`f`b
`B100`F9d9 int result = a + b;`f`b
`B100`F9d9 return result;`f`b
`B100`F9d9}`f`b

`B100`F9d9return`f`b statement ends execution immediately, except for one case: if the statement is encountered within a `B100`F9d9try`f`b block and it is complemented by a `B100`F9d9finally`f`b, control is passed to the `B100`F9d9finally`f`b block.

`B100`F9d9void doSomething(boolean streamClosed) {`f`b
`B100`F9d9 try {`f`b
`B100`F9d9 if (streamClosed) {`f`b
`B100`F9d9 return;`f`b
`B100`F9d9 }`f`b
`B100`F9d9 readFromStream();`f`b
`B100`F9d9 } finally {`f`b
`B100`F9d9 /* Will be called last even if`f`b
`B100`F9d9 readFromStream() was not called */`f`b
`B100`F9d9 freeResources();`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>>Exception handling statements

>>>>try-catch-finally statements

Exceptions are managed within `B100`F9d9try`f`b ... `B100`F9d9catch`f`b blocks.

`B100`F9d9try {`f`b
`B100`F9d9 // Statements that may throw exceptions`f`b
`B100`F9d9 methodThrowingExceptions();`f`b
`B100`F9d9} catch (Exception ex) {`f`b
`B100`F9d9 // Exception caught and handled here`f`b
`B100`F9d9 reportException(ex);`f`b
`B100`F9d9} finally {`f`b
`B100`F9d9 // Statements always executed after the try/catch blocks`f`b
`B100`F9d9 freeResources();`f`b
`B100`F9d9}`f`b

The statements within the `B100`F9d9try`f`b block are executed, and if any of them throws an exception, execution of the block is discontinued and the exception is handled by the `B100`F9d9catch`f`b block. There may be multiple `B100`F9d9catch`f`b blocks, in which case the first block with an exception variable whose type matches the type of the thrown exception is executed.

Java SE 7 also introduced multi-catch clauses besides uni-catch clauses. This type of catch clauses allows Java to handle different types of exceptions in a single block provided they are not subclasses of each other.

`B100`F9d9try {`f`b
`B100`F9d9 methodThrowingExceptions();`f`b
`B100`F9d9} catch (IOException | IllegalArgumentException ex) {`f`b
`B100`F9d9 //Both IOException and IllegalArgumentException will be caught and handled here`f`b
`B100`F9d9 reportException(ex);`f`b
`B100`F9d9}`f`b

If no `B100`F9d9catch`f`b block matches the type of the thrown exception, the execution of the outer block (or method) containing the `B100`F9d9try`f`b ... `B100`F9d9catch`f`b statement is discontinued, and the exception is passed up and outside the containing block (or method). The exception is propagated upwards through the `F33f`_`[call stack`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Call_stack]`_`f until a matching `B100`F9d9catch`f`b block is found within one of the currently active methods. If the exception propagates all the way up to the top-most `B100`F9d9main`f`b method without a matching `B100`F9d9catch`f`b block being found, a textual description of the exception is written to the standard output stream.

The statements within the `B100`F9d9finally`f`b block are always executed after the `B100`F9d9try`f`b and `B100`F9d9catch`f`b blocks, whether or not an exception was thrown and even if a `B100`F9d9return`f`b statement was reached. Such blocks are useful for providing cleanup code that is guaranteed to always be executed.

The `B100`F9d9catch`f`b and `B100`F9d9finally`f`b blocks are optional, but at least one or the other must be present following the `B100`F9d9try`f`b block.

>>>>try -with-resources statements

`B100`F9d9try`f`b-with-resources statements are a special type of `B100`F9d9try-catch-finally`f`b statements introduced as an implementation of the `F33f`_`[dispose pattern`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Dispose_pattern]`_`f in Java SE 7. In a `B100`F9d9try`f`b-with-resources statement the `B100`F9d9try`f`b keyword is followed by initialization of one or more resources that are released automatically when the `B100`F9d9try`f`b block execution is finished. Resources must implement `B100`F9d9java.lang.AutoCloseable`f`b. `B100`F9d9try`f`b-with-resources statements are not required to have a `B100`F9d9catch`f`b or `B100`F9d9finally`f`b block unlike normal `B100`F9d9try-catch-finally`f`b statements.

`B100`F9d9try (FileOutputStream fos = new FileOutputStream("filename");`f`b
`B100`F9d9 XMLEncoder xEnc = new XMLEncoder(fos)) {`f`b
`B100`F9d9 xEnc.writeObject(object);`f`b
`B100`F9d9} catch (IOException ex) {`f`b
`B100`F9d9 Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);`f`b
`B100`F9d9}`f`b

Since Java 9 it is possible to use already declared variables:

`B100`F9d9FileOutputStream fos = new FileOutputStream("filename");`f`b
`B100`F9d9XMLEncoder xEnc = new XMLEncoder(fos);`f`b
`B100`F9d9try (fos; xEnc) {`f`b
`B100`F9d9 xEnc.writeObject(object);`f`b
`B100`F9d9} catch (IOException ex) {`f`b
`B100`F9d9 Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);`f`b
`B100`F9d9}`f`b

>>>>throw statement

The `B100`F9d9throw`f`b statement is used to throw an exception and end the execution of the block or method. The thrown exception instance is written after the `B100`F9d9throw`f`b statement.

`B100`F9d9void methodThrowingExceptions(Object obj) {`f`b
`B100`F9d9 if (obj == null) {`f`b
`B100`F9d9 // Throws exception of NullPointerException type`f`b
`B100`F9d9 throw new NullPointerException();`f`b
`B100`F9d9 }`f`b
`B100`F9d9 // Will not be called, if object is null`f`b
`B100`F9d9 doSomethingWithObject(obj);`f`b
`B100`F9d9}`f`b

>>>Thread concurrency control

Java has built-in tools for `F33f`_`[multi-thread programming`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Thread_(computing)]`_`f. For the purposes of thread `F33f`_`[synchronization`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Synchronization_(computer_science)]`_`f the `B100`F9d9synchronized`f`b statement is included in Java language.

To make a code block synchronized, it is preceded by the `B100`F9d9synchronized`f`b keyword followed by the lock object inside the brackets. When the executing thread reaches the synchronized block, it acquires a `F33f`_`[mutual exclusion`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Mutual_exclusion]`_`f lock, executes the block, then releases the lock. No threads may enter this block until the lock is released. Any non-null reference type may be used as the lock.

`B100`F9d9/* Acquires lock on someObject. It must be of`f`b
`B100`F9d9a reference type and must be non-null */`f`b
`B100`F9d9synchronized (someObject) {`f`b
`B100`F9d9 // Synchronized statements`f`b
`B100`F9d9}`f`b

>>>assert statement

`B100`F9d9assert`f`b statements have been available since `F33f`_`[J2SE 1.4`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_1.4]`_`f. These types of statements are used to make `F33f`_`[assertions`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Assertion_(computing)]`_`f in the source code, which can be turned on and off during execution for specific classes or packages. To declare an assertion the `B100`F9d9assert`f`b keyword is used followed by a conditional expression. If it evaluates to `B100`F9d9false`f`b when the statement is executed, an exception is thrown. This statement can include a colon followed by another expression, which will act as the exception's detail message.

`B100`F9d9// If n equals 0, AssertionError is thrown`f`b
`B100`F9d9assert n != 0;`f`b
`B100`F9d9/* If n equals 0, AssertionError will be thrown`f`b
`B100`F9d9with the message after the colon */`f`b
`B100`F9d9assert n != 0 : "n was equal to zero";`f`b

>>Primitive types

Primitive types in Java include integer types, floating-point numbers, `F33f`_`[UTF-16`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=UTF-16]`_`f code units and a Boolean type. There are no unsigned types in Java except `B100`F9d9char`f`b type, which is used to represent UTF-16 code units. The lack of unsigned types is offset by introducing unsigned right shift operation (`B100`F9d9>>>`f`b), which is not present in C++. Nevertheless, criticisms have been leveled about the lack of compatibility with C and C++ this causes.`:cite-ref-3[`F5bf`_`[3`#cite-note-3]`_`f]

`t
| Primitive Types | Primitive Types | Primitive Types | Primitive Types | Primitive Types | Primitive Types |
|---|---|---|---|---|---|
| Type Name | Wrapper class | Value | Range | Size | Default Value |
| byte | java.lang.Byte | integer | −128 through +127 | 8-bit (1-byte) | 0 |
| short | java.lang.Short | integer | −32,768 through +32,767 | 16-bit (2-byte) | 0 |
| int | java.lang.Integer | integer | −2,147,483,648 through +2,147,483,647 | 32-bit (4-byte) | 0 |
| long | java.lang.Long | integer | −9,223,372,036,854,775,808 through +9,223,372,036,854,775,807 | 64-bit (8-byte) | 0 |
| float | java.lang.Float | floating point number | ±1.401298E−45 through ±3.402823E+38 | 32-bit (4-byte) | 0.0f [ 4 ] |
| double | java.lang.Double | floating point number | ±4.94065645841246E−324 through ±1.79769313486232E+308 | 64-bit (8-byte) | 0.0 |
| boolean | java.lang.Boolean | Boolean | true or false | 1-bit (1-bit) | false |
| char | java.lang.Character | UTF-16 code unit ( BMP character or a part of a surrogate pair) | '\\u0000' through '\\uFFFF' | 16-bit (2-byte) | '\\u0000' |
`t

`B100`F9d9char`f`b does not necessarily correspond to a single character. It may represent a part of a `F33f`_`[surrogate pair`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=UTF-16]`_`f, in which case Unicode code point is represented by a sequence of two `B100`F9d9char`f`b values.

>>>Boxing and unboxing

This language feature was introduced in `F33f`_`[J2SE 5.0`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_5.0]`_`f. `*Boxing`* is the operation of converting a value of a primitive type into a value of a corresponding reference type, which serves as a wrapper for this particular primitive type. `*Unboxing`* is the reverse operation of converting a value of a reference type (previously boxed) into a value of a corresponding primitive type. Neither operation requires an explicit conversion.

Example:

`B100`F9d9int foo = 42; // Primitive type`f`b
`B100`F9d9Integer bar = foo; /* foo is boxed to bar, bar is of Integer type,`f`b
`B100`F9d9 which serves as a wrapper for int */`f`b
`B100`F9d9int foo2 = bar; // Unboxed back to primitive type`f`b

>>Reference types

Reference types include class types, interface types, and array types. When the constructor is called, an object is created on the heap and a reference is assigned to the variable. When a variable of an object gets out of scope, the reference is broken and when there are no references left, the object gets marked as garbage. The garbage collector then collects and destroys it some time afterwards.

A reference variable is `B100`F9d9null`f`b when it does not reference any object.

>>>Arrays

Arrays in Java are created at runtime, just like class instances. Array length is defined at creation and cannot be changed.

`B100`F9d9int[] numbers = new int[5];`f`b
`B100`F9d9numbers[0] = 2;`f`b
`B100`F9d9numbers[1] = 5;`f`b
`B100`F9d9int x = numbers[0];`f`b

>>>>Initializers

`B100`F9d9// Long syntax`f`b
`B100`F9d9int[] numbers = new int[] {20, 1, 42, 15, 34};`f`b
`B100`F9d9// Short syntax`f`b
`B100`F9d9int[] numbers2 = {20, 1, 42, 15, 34};`f`b

>>>>Multi-dimensional arrays

In Java, multi-dimensional arrays are represented as arrays of arrays. Technically, they are represented by arrays of references to other arrays.

`B100`F9d9int[][] numbers = new int[3][3];`f`b
`B100`F9d9numbers[1][2] = 2;`f`b
`B100`F9d9`f`b
`B100`F9d9int[][] numbers2 = {{2, 3, 2}, {1, 2, 6}, {2, 4, 5}};`f`b

Due to the nature of the multi-dimensional arrays, sub-arrays can vary in length, so multi-dimensional arrays are not bound to be rectangular unlike C:

`B100`F9d9int[][] numbers = new int[2][]; //Initialization of the first dimension only`f`b
`B100`F9d9`f`b
`B100`F9d9numbers[0] = new int[3];`f`b
`B100`F9d9numbers[1] = new int[2];`f`b

>>>Classes

`F33f`_`[Classes`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Class_(computer_programming)]`_`f are fundamentals of an object-oriented language such as Java. They contain members that store and manipulate data. Classes are divided into `*top-level`* and `*nested`*. Nested classes are classes placed inside another class that may access the private members of the enclosing class. Nested classes include `*member classes`* (which may be defined with the `*static`* modifier for simple nesting or without it for inner classes), `*local classes`* and `*anonymous classes`*.

>>>>Declaration

`t
| Top-level class | class Foo { // Class members } |
|---|---|
| Inner class | class Foo { // Top-level class class Bar { // Inner class } } |
| Nested class | class Foo { // Top-level class static class Bar { // Nested class } } |
| Local class | class Foo { void bar () { class Foobar { // Local class within a method } } } |
| Anonymous class | class Foo { void bar () { new Object () { // Creation of a new anonymous class extending Object }; } } |
`t

>>>>Instantiation

Non-static members of a class define the types of the `F33f`_`[instance variables`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Instance_variable]`_`f and methods, which are related to the objects created from that class. To create these objects, the class must be instantiated by using the `B100`F9d9new`f`b operator and calling the class constructor.

`B100`F9d9Foo foo = new Foo();`f`b

>>>>Accessing members

Members of both instances and static classes are accessed with the `B100`F9d9.`f`b (dot) operator.

`!Accessing an instance member`!
Instance members can be accessed through the name of a variable.

`B100`F9d9String foo = "Hello";`f`b
`B100`F9d9String bar = foo.toUpperCase();`f`b

`!Accessing a static class member`!
Static members are accessed by using the name of the class or any other type. This does not require the creation of a class instance. Static members are declared using the `B100`F9d9static`f`b modifier.

`B100`F9d9public class Foo {`f`b
`B100`F9d9 public static void doSomething() {`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// Calling the static method`f`b
`B100`F9d9Foo.doSomething();`f`b

>>>>Modifiers

Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers.

• `!`B100`F9d9abstract`f`b`! - Specifies that a class only serves as a base class and cannot be instantiated.
• `!`B100`F9d9static`f`b`! - Used only for member classes, specifies that the member class does not belong to a specific instance of the containing class.
• `!`B100`F9d9final`f`b`! - Classes marked as `B100`F9d9final`f`b cannot be extended from and cannot have any subclasses.
• `!`B100`F9d9strictfp`f`b`! - Specifies that all floating-point operations must be carried out conforming to `F33f`_`[IEEE 754`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=IEEE_754]`_`f and forbids using enhanced precision to store intermediate results.

>>>>Abstract class

By default, all methods in all classes are concrete, unless the abstract keyword is used. An abstract class may include abstract methods, which have no implementation. By default, all methods in all interfaces are abstract, unless the default keyword is used. The default keyword can be used to specify a concrete method in an interface.

`B100`F9d9//By default, all methods in all classes are concrete, unless the abstract keyword is used.`f`b
`B100`F9d9public abstract class Demo {`f`b
`B100`F9d9 // An abstract class may include abstract methods, which have no implementation.`f`b
`B100`F9d9 public abstract int sum(int x, int y);`f`b
`B100`F9d9`f`b
`B100`F9d9 // An abstract class may also include concrete methods.`f`b
`B100`F9d9 public int product(int x, int y) {`f`b
`B100`F9d9 return x*y;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9//By default, all methods in all interfaces are abstract, unless the default keyword is used.`f`b
`B100`F9d9interface DemoInterface {`f`b
`B100`F9d9 int getLength(); //The abstract keyword can be used here, though is completely useless`f`b
`B100`F9d9`f`b
`B100`F9d9 //The default keyword can be used in this context to specify a concrete method in an interface`f`b
`B100`F9d9 default int product(int x, int y) {`f`b
`B100`F9d9 return x * y;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>>>Final class

A final `F33f`_`[class`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Class_(computer_science)]`_`f cannot be subclassed. As doing this can confer security and efficiency benefits, many of the Java standard library classes are final, such as `B100`F9d9java.lang.System`f`b and `B100`F9d9java.lang.String`f`b.

Example:

`B100`F9d9public final class MyFinalClass {...}`f`b
`B100`F9d9`f`b
`B100`F9d9public class ThisIsWrong extends MyFinalClass {...} // forbidden`f`b

>>>>Access modifiers

The `*access modifiers`*, or `*inheritance modifiers`*, set the accessibility of classes, methods, and other members. Members marked as `B100`F9d9public`f`b can be reached from anywhere. If a class or its member does not have any modifiers, default access is assumed.

`B100`F9d9public class Foo {`f`b
`B100`F9d9 int go() {`f`b
`B100`F9d9 return 0;`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 private class Bar {`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

The following table shows whether code within a class has access to the class or method depending on the accessing class location and the modifier for the accessed class or class member:

`t
| Modifier | Same class or nested class | Other class inside the same package | Extended Class inside another package | Non-extended inside another package |
|---|---|---|---|---|
| private | yes | no | no | no |
| default (package private) | yes | yes | no | no |
| protected | yes | yes | yes | no |
| public | yes | yes | yes | yes |
`t

>>>>Constructors and initializers

A `F33f`_`[constructor`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Constructor_(object-oriented_programming)]`_`f is a special method called when an object is initialized. Its purpose is to initialize the members of the object. The main differences between constructors and ordinary methods are that constructors are called only when an instance of the class is created and never return anything. Constructors are declared as common methods, but they are named after the class and no return type is specified:

`B100`F9d9class Foo {`f`b
`B100`F9d9 String str;`f`b
`B100`F9d9`f`b
`B100`F9d9 Foo() { // Constructor with no arguments`f`b
`B100`F9d9`f`b
`B100`F9d9 // Initialization`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 Foo(String str) { // Constructor with one argument`f`b
`B100`F9d9 this.str = str;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

Initializers are blocks of code that are executed when a class or an instance of a class is created. There are two kinds of initializers, `*static initializers`* and `*instance initializers`*.

Static initializers initialize static fields when the class is created. They are declared using the `B100`F9d9static`f`b keyword:

`B100`F9d9class Foo {`f`b
`B100`F9d9 static {`f`b
`B100`F9d9 // Initialization`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

A class is created only once. Therefore, static initializers are not called more than once. On the contrary, instance initializers are automatically called before the call to a constructor every time an instance of the class is created. Unlike constructors instance initializers cannot take any arguments and generally they cannot throw any `F33f`_`[checked exceptions`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Exception_handling]`_`f (except in several special cases). Instance initializers are declared in a block without any keywords:

`B100`F9d9class Foo {`f`b
`B100`F9d9 {`f`b
`B100`F9d9 // Initialization`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

Since Java has a garbage collection mechanism, there are no `F33f`_`[destructors`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Destructor_(computer_science)]`_`f. However, every object has a `B100`F9d9finalize()`f`b method called prior to garbage collection, which can be `F33f`_`[overridden`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Method_overriding]`_`f to implement finalization.

>>>>Methods

All the statements in Java must reside within `F33f`_`[methods`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Method_(computer_programming)]`_`f. Methods are similar to functions except they belong to classes. A method has a return value, a name and usually some parameters initialized when it is called with some arguments. Similar to C++, methods returning nothing have return type declared as `B100`F9d9void`f`b. Unlike in C++, methods in Java are not allowed to have `F33f`_`[default argument`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Default_argument]`_`f values and methods are usually overloaded instead.

`B100`F9d9class Foo {`f`b
`B100`F9d9 int bar(int a, int b) {`f`b
`B100`F9d9 return (a*2) + b;`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 /* Overloaded method with the same name but different set of arguments */`f`b
`B100`F9d9 int bar(int a) {`f`b
`B100`F9d9 return a*2;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

A method is called using `B100`F9d9.`f`b notation on an object, or in the case of a static method, also on the name of a class.

`B100`F9d9Foo foo = new Foo();`f`b
`B100`F9d9int result = foo.bar(7, 2); // Non-static method is called on foo`f`b
`B100`F9d9`f`b
`B100`F9d9int finalResult = Math.abs(result); // Static method call`f`b

The `B100`F9d9throws`f`b keyword indicates that a method throws an exception. All checked exceptions must be listed in a comma-separated list.

`B100`F9d9void openStream() throws IOException, myException { // Indicates that IOException may be thrown`f`b
`B100`F9d9}`f`b

>>>>Modifiers

• `!`B100`F9d9abstract`f`b`! - `F33f`_`[Abstract methods`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Abstract_method]`_`f can be present only in `F33f`_`[abstract classes`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Abstract_class]`_`f, such methods have no body and must be overridden in a subclass unless it is abstract itself.
• `!`B100`F9d9static`f`b`! - Makes the method static and accessible without creation of a class instance. However static methods cannot access non-static members in the same class.
• `!`B100`F9d9final`f`b`! - Declares that the method cannot be overridden in a subclass.
• `!`B100`F9d9native`f`b`! - Indicates that this method is implemented through `F33f`_`[JNI`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=JNI]`_`f in platform-dependent code. Actual implementation happens outside Java code, and such methods have no body.
• `!`B100`F9d9strictfp`f`b`! - Declares strict conformance to `F33f`_`[IEEE 754`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=IEEE_754]`_`f in carrying out floating-point operations.
• `!`B100`F9d9synchronized`f`b`! - Declares that a thread executing this method must acquire monitor. For `B100`F9d9synchronized`f`b methods the monitor is the class instance or `B100`F9d9java.lang.Class`f`b if the method is static.
• Access modifiers - Identical to those used with classes.

>>>>Final methods

A final `F33f`_`[method`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Method_(computer_science)]`_`f cannot be `F33f`_`[overridden`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Method_overriding]`_`f or hidden by subclasses.`:cite-ref-5[`F5bf`_`[5`#cite-note-5]`_`f] This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.`:cite-ref-6[`F5bf`_`[6`#cite-note-6]`_`f]

Example:

`B100`F9d9public class Base`f`b
`B100`F9d9{`f`b
`B100`F9d9 public void m1() {...}`f`b
`B100`F9d9 public final void m2() {...}`f`b
`B100`F9d9`f`b
`B100`F9d9 public static void m3() {...}`f`b
`B100`F9d9 public static final void m4() {...}`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9public class Derived extends Base`f`b
`B100`F9d9{`f`b
`B100`F9d9 public void m1() {...} // OK, overriding Base#m1()`f`b
`B100`F9d9 public void m2() {...} // forbidden`f`b
`B100`F9d9`f`b
`B100`F9d9 public static void m3() {...} // OK, hiding Base#m3()`f`b
`B100`F9d9 public static void m4() {...} // forbidden`f`b
`B100`F9d9}`f`b

A common misconception is that declaring a method as `B100`F9d9final`f`b improves efficiency by allowing the compiler to directly insert the method wherever it is called (see `F33f`_`[inline expansion`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Inline_expansion]`_`f). Because the method is loaded at `F33f`_`[runtime`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Run_time_(program_lifecycle_phase)]`_`f, compilers are unable to do this. Only the runtime environment and `F33f`_`[JIT`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Just-in-time_compilation]`_`f compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.`:cite-ref-7[`F5bf`_`[7`#cite-note-7]`_`f]

Machine code compilers that generate directly executable, platform-specific

machine code

, are an exception. When using

static linking

, the compiler can safely assume that methods and variables computable at

compile-time

may be inlined.

>>>>Varargs

This language feature was introduced in `F33f`_`[J2SE 5.0`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_5.0]`_`f. The last argument of the method may be declared as a variable arity parameter, in which case the method becomes a variable arity method (as opposed to fixed arity methods) or simply `F33f`_`[varargs`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Variadic_function]`_`f method. This allows one to pass a variable number of values, of the declared type, to the method as parameters - including no parameters. These values will be available inside the method as an array.

`B100`F9d9void printReport(String header, int... numbers) { //numbers represents varargs`f`b
`B100`F9d9 System.out.println(header);`f`b
`B100`F9d9 for (int num : numbers) {`f`b
`B100`F9d9 System.out.println(num);`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// Calling varargs method`f`b
`B100`F9d9printReport("Report data", 74, 83, 25, 96);`f`b

>>>>Fields

Fields, or `F33f`_`[class variables`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Class_variable]`_`f, can be declared inside the class body to store data.

`B100`F9d9class Foo {`f`b
`B100`F9d9 double bar;`f`b
`B100`F9d9}`f`b

Fields can be initialized directly when declared.

`B100`F9d9class Foo {`f`b
`B100`F9d9 double bar = 2.3;`f`b
`B100`F9d9}`f`b

>>>>Modifiers

• `!`B100`F9d9static`f`b`! - Makes the field a static member.
• `!`B100`F9d9final`f`b`! - Allows the field to be initialized only once in a constructor or inside initialization block or during its declaration, whichever is earlier.
• `!`B100`F9d9transient`f`b`! - Indicates that this field will not be stored during `F33f`_`[serialization`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Serialization]`_`f.
• `!`B100`F9d9volatile`f`b`! - If a field is declared `B100`F9d9volatile`f`b, it is ensured that all threads see a consistent value for the variable.

>>>>Inheritance

Classes in Java can only `F33f`_`[inherit`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Inheritance_(object-oriented_programming)]`_`f from `*one`* class. A class can be derived from any class that is not marked as `B100`F9d9final`f`b. Inheritance is declared using the `B100`F9d9extends`f`b keyword. A class can reference itself using the `B100`F9d9this`f`b keyword and its direct superclass using the `B100`F9d9super`f`b keyword.

`B100`F9d9class Foo {`f`b
`B100`F9d9`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9class Foobar extends Foo {`f`b
`B100`F9d9`f`b
`B100`F9d9}`f`b

If a class does not specify its superclass, it implicitly inherits from `B100`F9d9java.lang.Object`f`b class. Thus all classes in Java are subclasses of `B100`F9d9Object`f`b class.

If the superclass does not have a constructor without parameters the subclass must specify in its constructors what constructor of the superclass to use. For example:

`B100`F9d9class Foo {`f`b
`B100`F9d9 public Foo(int n) {`f`b
`B100`F9d9 // Do something with n`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9class Foobar extends Foo {`f`b
`B100`F9d9 private int number;`f`b
`B100`F9d9 // Superclass does not have constructor without parameters`f`b
`B100`F9d9 // so we have to specify what constructor of our superclass to use and how`f`b
`B100`F9d9`f`b
`B100`F9d9 public Foobar(int number) {`f`b
`B100`F9d9 super(number);`f`b
`B100`F9d9 this.number = number;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>>>Overriding methods

Unlike C++, all non-`B100`F9d9final`f`b methods in Java are `F33f`_`[virtual`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Virtual_function]`_`f and can be overridden by the inheriting classes.

`B100`F9d9class Operation {`f`b
`B100`F9d9 public int doSomething() {`f`b
`B100`F9d9 return 0;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9class NewOperation extends Operation {`f`b
`B100`F9d9 @Override`f`b
`B100`F9d9 public int doSomething() {`f`b
`B100`F9d9 return 1;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>>>Abstract classes

An Abstract Class is a class that is incomplete, or is to be considered incomplete, so cannot be instantiated.

A class C has abstract methods if any of the following is true:

• C explicitly contains a declaration of an abstract method.
• Any of C's superclasses has an abstract method and C neither declares nor inherits a method that implements it.
• A direct superinterface of C declares or inherits a method (which is therefore necessarily abstract) and C neither declares nor inherits a method that implements it.
• A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class.

`B100`F9d9package org.dwwwp.test;`f`b
`B100`F9d9`f`b
`B100`F9d9/**`f`b
`B100`F9d9 * @author jcrypto`f`b
`B100`F9d9 */`f`b
`B100`F9d9public class AbstractClass {`f`b
`B100`F9d9 private static final String hello;`f`b
`B100`F9d9`f`b
`B100`F9d9 static {`f`b
`B100`F9d9 System.out.println(AbstractClass.class.getName() + ": static block runtime");`f`b
`B100`F9d9 hello = "hello from " + AbstractClass.class.getName();`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 {`f`b
`B100`F9d9 System.out.println(AbstractClass.class.getName() + ": instance block runtime");`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 public AbstractClass() {`f`b
`B100`F9d9 System.out.println(AbstractClass.class.getName() + ": constructor runtime");`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 public static void hello() {`f`b
`B100`F9d9 System.out.println(hello);`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

`B100`F9d9package org.dwwwp.test;`f`b
`B100`F9d9`f`b
`B100`F9d9/**`f`b
`B100`F9d9 * @author jcrypto`f`b
`B100`F9d9 */`f`b
`B100`F9d9public class CustomClass extends AbstractClass {`f`b
`B100`F9d9`f`b
`B100`F9d9 static {`f`b
`B100`F9d9 System.out.println(CustomClass.class.getName() + ": static block runtime");`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 {`f`b
`B100`F9d9 System.out.println(CustomClass.class.getName() + ": instance block runtime");`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 public CustomClass() {`f`b
`B100`F9d9 System.out.println(CustomClass.class.getName() + ": constructor runtime");`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 public static void main(String[] args) {`f`b
`B100`F9d9 CustomClass nc = new CustomClass();`f`b
`B100`F9d9 hello();`f`b
`B100`F9d9 //AbstractClass.hello();//also valid`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

Output:

`B100`F9d9org.dwwwp.test.AbstractClass: static block runtime`f`b
`B100`F9d9org.dwwwp.test.CustomClass: static block runtime`f`b
`B100`F9d9org.dwwwp.test.AbstractClass: instance block runtime`f`b
`B100`F9d9org.dwwwp.test.AbstractClass: constructor runtime`f`b
`B100`F9d9org.dwwwp.test.CustomClass: instance block runtime`f`b
`B100`F9d9org.dwwwp.test.CustomClass: constructor runtime`f`b
`B100`F9d9hello from org.dwwwp.test.AbstractClass`f`b

>>>>Enumerations

This language feature was introduced in `F33f`_`[J2SE 5.0`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_5.0]`_`f. Technically enumerations are a kind of class containing enum constants in its body. Each enum constant defines an instance of the enum type. Enumeration classes cannot be instantiated anywhere except in the enumeration class itself.

`B100`F9d9enum Season {`f`b
`B100`F9d9 WINTER, SPRING, SUMMER, AUTUMN`f`b
`B100`F9d9}`f`b

Enum constants are allowed to have constructors, which are called when the class is loaded:

`B100`F9d9public enum Season {`f`b
`B100`F9d9 WINTER("Cold"), SPRING("Warmer"), SUMMER("Hot"), AUTUMN("Cooler");`f`b
`B100`F9d9`f`b
`B100`F9d9 Season(String description) {`f`b
`B100`F9d9 this.description = description;`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 private final String description;`f`b
`B100`F9d9`f`b
`B100`F9d9 public String getDescription() {`f`b
`B100`F9d9 return description;`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class:

`B100`F9d9public enum Season {`f`b
`B100`F9d9 WINTER {`f`b
`B100`F9d9 String getDescription() {return "cold";}`f`b
`B100`F9d9 },`f`b
`B100`F9d9 SPRING {`f`b
`B100`F9d9 String getDescription() {return "warmer";}`f`b
`B100`F9d9 },`f`b
`B100`F9d9 SUMMER {`f`b
`B100`F9d9 String getDescription() {return "hot";}`f`b
`B100`F9d9 },`f`b
`B100`F9d9 FALL {`f`b
`B100`F9d9 String getDescription() {return "cooler";}`f`b
`B100`F9d9 };`f`b
`B100`F9d9}`f`b

>>>Interfaces

`F33f`_`[Interfaces`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Interface_(Java)]`_`f are types which contain no fields and usually define a number of methods without an actual implementation. They are useful to define a contract with any number of different implementations. Every interface is implicitly abstract. Interface methods are allowed to have a subset of access modifiers depending on the language version, `B100`F9d9strictfp`f`b, which has the same effect as for classes, and also `B100`F9d9static`f`b since Java SE 8.

`B100`F9d9interface ActionListener {`f`b
`B100`F9d9 int ACTION_ADD = 0;`f`b
`B100`F9d9 int ACTION_REMOVE = 1;`f`b
`B100`F9d9`f`b
`B100`F9d9 void actionSelected(int action);`f`b
`B100`F9d9}`f`b

>>>>Implementing an interface

An interface is implemented by a class using the `B100`F9d9implements`f`b keyword. It is allowed to implement more than one interface, in which case they are written after `B100`F9d9implements`f`b keyword in a comma-separated list. A class implementing an interface must override all its methods, otherwise it must be declared as abstract.

`B100`F9d9interface RequestListener {`f`b
`B100`F9d9 int requestReceived();`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9class ActionHandler implements ActionListener, RequestListener {`f`b
`B100`F9d9 public void actionSelected(int action) {`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 public int requestReceived() {`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9//Calling method defined by interface`f`b
`B100`F9d9RequestListener listener = new ActionHandler(); /*ActionHandler can be`f`b
`B100`F9d9 represented as RequestListener...*/`f`b
`B100`F9d9listener.requestReceived(); /*...and thus is known to implement`f`b
`B100`F9d9 requestReceived() method*/`f`b

>>>>Functional interfaces and lambda expressions

These features were introduced with the release of Java SE 8. An interface automatically becomes a functional interface if it defines only one method. In this case an implementation can be represented as a lambda expression instead of implementing it in a new class, thus greatly simplifying writing code in the `F33f`_`[functional style`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Functional_programming]`_`f. Functional interfaces can optionally be annotated with the `B100`F9d9`F33f`_`[@FunctionalInterface`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=@FunctionalInterface]`_`f`f`b annotation, which will tell the compiler to check whether the interface actually conforms to a definition of a functional interface.

`B100`F9d9// A functional interface`f`b
`B100`F9d9@FunctionalInterface`f`b
`B100`F9d9interface Calculation {`f`b
`B100`F9d9 int calculate(int someNumber, int someOtherNumber);`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// A method which accepts this interface as a parameter`f`b
`B100`F9d9int runCalculation(Calculation calculation) {`f`b
`B100`F9d9 return calculation.calculate(1, 2);`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// Using a lambda to call the method`f`b
`B100`F9d9runCalculation((number, otherNumber) -> number + otherNumber);`f`b
`B100`F9d9`f`b
`B100`F9d9// Equivalent code which uses an anonymous class instead`f`b
`B100`F9d9runCalculation(new Calculation() {`f`b
`B100`F9d9 @Override`f`b
`B100`F9d9 public int calculate(int someNumber, int someOtherNumber) {`f`b
`B100`F9d9 return someNumber + someOtherNumber;`f`b
`B100`F9d9 }`f`b
`B100`F9d9})`f`b

Lambda's parameters types do not have to be fully specified and can be inferred from the interface it implements. Lambda's body can be written without a body block and a `B100`F9d9return`f`b statement if it is only an expression. Also, for those interfaces which only have a single parameter in the method, round brackets can be omitted.`:cite-ref-8[`F5bf`_`[8`#cite-note-8]`_`f]

`B100`F9d9// Same call as above, but with fully specified types and a body block`f`b
`B100`F9d9runCalculation((int number, int otherNumber) -> {`f`b
`B100`F9d9 return number + otherNumber;`f`b
`B100`F9d9});`f`b
`B100`F9d9`f`b
`B100`F9d9// A functional interface with a method which has only a single parameter`f`b
`B100`F9d9interface StringExtender {`f`b
`B100`F9d9 String extendString(String input);`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// Initializing a variable of this type by using a lambda`f`b
`B100`F9d9StringExtender extender = input -> input + " Extended";`f`b

>>>>Method references

It is not necessary to use lambdas when there already is a named method compatible with the interface. This method can be passed instead of a lambda using a method reference. There are several types of method references:

`t
| Reference type | Example | Equivalent lambda |
|---|---|---|
| Static | Integer::sum | (number, otherNumber) -> number + otherNumber |
| Bound | "LongString"::substring | index -> "LongString".substring(index) |
| Unbound | String::isEmpty | string -> string.isEmpty() |
| Class constructor | ArrayList<String>::new | capacity -> new ArrayList<String>(capacity) |
| Array constructor | String[]::new | size -> new String[size] |
`t

The code above which calls `B100`F9d9runCalculation`f`b could be replaced with the following using the method references:

`B100`F9d9runCalculation(Integer::sum);`f`b

>>>>Inheritance

Interfaces can inherit from other interfaces just like classes. Unlike classes it is allowed to inherit from multiple interfaces. However, it is possible that several interfaces have a field with the same name, in which case it becomes a single ambiguous member, which cannot be accessed.

`B100`F9d9/* Class implementing this interface must implement methods of both`f`b
`B100`F9d9ActionListener and RequestListener */`f`b
`B100`F9d9interface EventListener extends ActionListener, RequestListener {`f`b
`B100`F9d9}`f`b

>>>>Default methods

Java SE 8 introduced default methods to interfaces which allows developers to add new methods to existing interfaces without breaking compatibility with the classes already implementing the interface. Unlike regular interface methods, default methods have a body which will get called in the case if the implementing class does not override it.

`B100`F9d9interface StringManipulator {`f`b
`B100`F9d9 String extendString(String input);`f`b
`B100`F9d9`f`b
`B100`F9d9 // A method which is optional to implement`f`b
`B100`F9d9 default String shortenString(String input) {`f`b
`B100`F9d9 return input.substring(1);`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// This is a valid class despite not implementing all the methods`f`b
`B100`F9d9class PartialStringManipulator implements StringManipulator {`f`b
`B100`F9d9 @Override`f`b
`B100`F9d9 public String extendString(String input) {`f`b
`B100`F9d9 return input + " Extended";`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>>>Static methods

Static methods is another language feature introduced in Java SE 8. They behave in exactly the same way as in the classes.

`B100`F9d9interface StringUtils {`f`b
`B100`F9d9 static String shortenByOneSymbol(String input) {`f`b
`B100`F9d9 return input.substring(1);`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9StringUtils.shortenByOneSymbol("Test");`f`b

>>>>Private methods

Private methods were added in the Java 9 release. An interface can have a method with a body marked as private, in which case it will not be visible to inheriting classes. It can be called from default methods for the purposes of code reuse.

`B100`F9d9interface Logger {`f`b
`B100`F9d9 default void logError() {`f`b
`B100`F9d9 log(Level.ERROR);`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 default void logInfo() {`f`b
`B100`F9d9 log(Level.INFO);`f`b
`B100`F9d9 }`f`b
`B100`F9d9`f`b
`B100`F9d9 private void log(Level level) {`f`b
`B100`F9d9 SystemLogger.log(level.id);`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>>>Annotations

Annotations in Java are a way to embed `F33f`_`[metadata`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Metadata]`_`f into code. This language feature was introduced in `F33f`_`[J2SE 5.0`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_5.0]`_`f.

>>>>Annotation types

Java has a set of predefined annotation types, but it is allowed to define new ones. An annotation type declaration is a special type of an interface declaration. They are declared in the same way as the interfaces, except the `B100`F9d9interface`f`b keyword is preceded by the `B100`F9d9@`f`b sign. All annotations are implicitly extended from `B100`F9d9java.lang.annotation.Annotation`f`b and cannot be extended from anything else.

`B100`F9d9@interface BlockingOperations {`f`b
`B100`F9d9}`f`b

Annotations may have the same declarations in the body as the common interfaces, in addition they are allowed to include enums and annotations. The main difference is that abstract method declarations must not have any parameters or throw any exceptions. Also they may have a default value, which is declared using the `B100`F9d9default`f`b keyword after the method name:

`B100`F9d9@interface BlockingOperations {`f`b
`B100`F9d9 boolean fileSystemOperations();`f`b
`B100`F9d9 boolean networkOperations() default false;`f`b
`B100`F9d9}`f`b

>>>>Usage of annotations

Annotations may be used in any kind of declaration, whether it is package, class (including enums), interface (including annotations), field, method, parameter, constructor, or local variable. Also they can be used with enum constants. Annotations are declared using the `B100`F9d9@`f`b sign preceding annotation type name, after which element-value pairs are written inside brackets. All elements with no default value must be assigned a value.

`B100`F9d9@BlockingOperations(/*mandatory*/ fileSystemOperations,`f`b
`B100`F9d9/*optional*/ networkOperations = true)`f`b
`B100`F9d9void openOutputStream() { //Annotated method`f`b
`B100`F9d9}`f`b

Besides the generic form, there are two other forms to declare an annotation, which are shorthands. `*Marker annotation`* is a short form, it is used when no values are assigned to elements:

`B100`F9d9@Unused // Shorthand for @Unused()`f`b
`B100`F9d9void travelToJupiter() {`f`b
`B100`F9d9}`f`b

The other short form is called `*single element annotation`*. It is used with annotations types containing only one element or in the case when multiple elements are present, but only one elements lacks a default value. In single element annotation form the element name is omitted and only value is written instead:

`B100`F9d9/* Equivalent for @BlockingOperations(fileSystemOperations = true).`f`b
`B100`F9d9networkOperations has a default value and`f`b
`B100`F9d9does not have to be assigned a value */`f`b
`B100`F9d9`f`b
`B100`F9d9@BlockingOperations(true)`f`b
`B100`F9d9void openOutputStream() {`f`b
`B100`F9d9}`f`b

>>Generics

`F33f`_`[Generics`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Generic_programming]`_`f, or parameterized types, or `F33f`_`[parametric polymorphism`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Parametric_polymorphism]`_`f, is one of the major features introduced in `F33f`_`[J2SE 5.0`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=J2SE_5.0]`_`f. Before generics were introduced, it was required to declare all the types explicitly. With generics, it became possible to work in a similar manner with different types without declaring the exact types. The main purpose of generics is to ensure type safety and to detect runtime errors during compilation. Unlike C#, information on the used parameters is not available at runtime due to `F33f`_`[type erasure`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Type_erasure]`_`f.`:cite-ref-9[`F5bf`_`[9`#cite-note-9]`_`f]

>>>Generic classes

Classes can be parameterized by adding a type variable inside angle brackets (`B100`F9d9<`f`b and `B100`F9d9>`f`b) following the class name. It makes possible the use of this type variable in class members instead of actual types. There can be more than one type variable, in which case they are declared in a comma-separated list.

It is possible to limit a type variable to a subtype of some specific class or declare an interface that must be implemented by the type. In this case the type variable is appended by the `B100`F9d9extends`f`b keyword followed by a name of the class or the interface. If the variable is constrained by both class and interface or if there are several interfaces, the class name is written first, followed by interface names with `B100`F9d9& `f`b sign used as the delimiter.

`B100`F9d9/* This class has two type variables, T and V. T must be`f`b
`B100`F9d9a subtype of ArrayList and implement Formattable interface */`f`b
`B100`F9d9public class Mapper<T extends ArrayList & Formattable, V> {`f`b
`B100`F9d9 public void add(T array, V item) {`f`b
`B100`F9d9 // array has add method because it is an ArrayList subclass`f`b
`B100`F9d9 array.add(item);`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

When a variable of a parameterized type is declared or an instance is created, its type is written exactly in the same format as in the class header, except the actual type is written in the place of the type variable declaration.

`B100`F9d9/* Mapper is created with CustomList as T and Integer as V.`f`b
`B100`F9d9CustomList must be a subclass of ArrayList and implement Formattable */`f`b
`B100`F9d9Mapper<CustomList, Integer> mapper = new Mapper<CustomList, Integer>();`f`b

Since Java SE 7, it is possible to use a diamond (`B100`F9d9<>`f`b) in place of type arguments, in which case the latter will be inferred. The following code in Java SE 7 is equivalent to the code in the previous example:

`B100`F9d9Mapper<CustomList, Integer> mapper = new Mapper<>();`f`b

When declaring a variable for a parameterized type, it is possible to use wildcards instead of explicit type names. Wildcards are expressed by writing `B100`F9d9?`f`b sign instead of the actual type. It is possible to limit possible types to the subclasses or superclasses of some specific class by writing the `B100`F9d9extends`f`b keyword or the `B100`F9d9super`f`b keyword correspondingly followed by the class name.

`B100`F9d9/* Any Mapper instance with CustomList as the first parameter`f`b
`B100`F9d9may be used regardless of the second one.*/`f`b
`B100`F9d9Mapper<CustomList, ?> mapper;`f`b
`B100`F9d9mapper = new Mapper<CustomList, Boolean>();`f`b
`B100`F9d9mapper = new Mapper<CustomList, Integer>();`f`b
`B100`F9d9`f`b
`B100`F9d9/* Will not accept types that use anything but`f`b
`B100`F9d9a subclass of Number as the second parameter */`f`b
`B100`F9d9void addMapper(Mapper<?, ? extends Number> mapper) {`f`b
`B100`F9d9}`f`b

>>>Generic methods and constructors

Usage of generics may be limited to some particular methods, this concept applies to constructors as well. To declare a parameterized method, type variables are written before the return type of the method in the same format as for the generic classes. In the case of constructor, type variables are declared before the constructor name.

`B100`F9d9class Mapper {`f`b
`B100`F9d9 // The class itself is not generic, the constructor is`f`b
`B100`F9d9 <T, V> Mapper(T array, V item) {`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9/* This method will accept only arrays of the same type as`f`b
`B100`F9d9the searched item type or its subtype*/`f`b
`B100`F9d9static <T, V extends T> boolean contains(T item, V[] arr) {`f`b
`B100`F9d9 for (T currentItem : arr) {`f`b
`B100`F9d9 if (item.equals(currentItem)) {`f`b
`B100`F9d9 return true;`f`b
`B100`F9d9 }`f`b
`B100`F9d9 }`f`b
`B100`F9d9 return false;`f`b
`B100`F9d9}`f`b

>>>Generic interfaces

Interfaces can be parameterized in the similar manner as the classes.

`B100`F9d9interface Expandable<T extends Number> {`f`b
`B100`F9d9 void addItem(T item);`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// This class is parameterized`f`b
`B100`F9d9class Array<T extends Number> implements Expandable<T> {`f`b
`B100`F9d9 void addItem(T item) {`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b
`B100`F9d9`f`b
`B100`F9d9// And this is not and uses an explicit type instead`f`b
`B100`F9d9class IntegerArray implements Expandable<Integer> {`f`b
`B100`F9d9 void addItem(Integer item) {`f`b
`B100`F9d9 }`f`b
`B100`F9d9}`f`b

>>See also

• `F33f`_`[Java Platform, Standard Edition`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Java_Platform,_Standard_Edition]`_`f
• `F33f`_`[C Sharp syntax`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C_Sharp_syntax]`_`f
• `F33f`_`[C++ syntax`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C++_syntax]`_`f
• `F33f`_`[C syntax`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=C_syntax]`_`f

>>References

`:cite-note-1`!1.`! "Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)". `*docs.oracle.com`*. Oracle and/or its affiliates. Archived from the original on June 24, 2015. Retrieved June 16, 2015.
`:cite-note-2`!2.`! `F0af`_`[↑`#cite-ref-2]`_`f "The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)". `*docs.oracle.com`*. Archived from the original on March 15, 2010. Retrieved August 15, 2021.
`:cite-note-3`!3.`! `F0af`_`[↑`#cite-ref-3]`_`f `:citerefowens`aOwens, Sean. "Java and unsigned int, unsigned short, unsigned byte, unsigned long, etc. (Or rather, the lack thereof)". Archived from the original on February 20, 2009. Retrieved April 21, 2010.
`:cite-note-4`!2.`! "Primitive Data Types".
`:cite-note-5`!5.`! `F0af`_`[↑`#cite-ref-5]`_`f "Chapter 8. Classes". `*docs.oracle.com`*. Retrieved April 25, 2024.
`:cite-note-6`!6.`! `F0af`_`[↑`#cite-ref-6]`_`f "Writing Final Classes and Methods". `*docs.oracle.com`*. Retrieved April 25, 2024.
`:cite-note-7`!7.`! `F0af`_`[↑`#cite-ref-7]`_`f "Java theory and practice: Is that your final answer?". `*developer.ibm.com`*. Archived from the original on February 8, 2009. Retrieved April 25, 2024.
`:cite-note-8`!8.`! `F0af`_`[↑`#cite-ref-8]`_`f "Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)". `*docs.oracle.com`*. Archived from the original on June 16, 2020. Retrieved August 8, 2021.
`:cite-note-9`!9.`! `F0af`_`[↑`#cite-ref-9]`_`f "Generics in the Run Time (C# Programming Guide)". Archived from the original on March 10, 2016. Retrieved March 9, 2016.

• `:citerefnaughtonschildt1999`a`F33f`_`[Naughton, Patrick`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Patrick_Naughton]`_`f; `F33f`_`[Schildt, Herbert`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Herbert_Schildt]`_`f (1999). `*Java 2: The Complete Reference`* (3rd ed.). The McGraw-Hill Companies. `F33f`_`[ISBN`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=ISBN_(identifier)]`_`f 0-07-211976-4.
• `:citerefvermeulenamblerbumgardnermetz2000`aVermeulen; Ambler; Bumgardner; Metz; Misfeldt; Shur; Thompson (2000). `*The Elements of Java Style`*. Cambridge University Press. `F33f`_`[ISBN`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=ISBN_(identifier)]`_`f 0-521-77768-2.
• `:citerefgoslingjoysteelebracha2005`a`F33f`_`[Gosling, James`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=James_Gosling]`_`f; `F33f`_`[Joy, Bill`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Bill_Joy]`_`f; `F33f`_`[Steele, Guy`:/page/wikibook/entry.mu`zim=wikipedia_en_all_nopic_2025-08.zim|entry_path=Guy_L._Steele_Jr.]`_`f; Bracha, Gilad (2005). `*Java Language Specification`* (3rd ed.). Addison-Wesley Professional. Archived from the original on February 26, 2009. Retrieved December 3, 2008.

>>External links

Wikibooks has a book on the topic of:

Java Programming/Syntax

• The Java Language Specification, Third edition Authoritative description of the Java language
• Java SE 24 API Javadocs

`c`F0af`_`[↑ Back to top`#top]`_`f`a